﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using System.Collections;

using System.IO;
using System.Net;
using System.Net.Cache;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;


namespace LCWMS
{
    public partial class  w_so061 : DockContent
    {
        DataSet dscustomer;
        DataSet ds_tran;

        Cursor currentCursor = Cursor.Current;

        private static int iJS = 0;
        private static int iJSset = 300;



        public w_so061()
        {
            InitializeComponent();
            dgv_tran.AutoGenerateColumns = false;
        }
       

        private void btn_Query_Click(object sender, EventArgs e)
        {
            //querydata(); 同步过来的监控数据（原来）

            querydata_wms(); // wms的数据（新）
        }


        //添加合计行
        private void f_add()
        {
            decimal d_1 = 0, d_2 = 0, d_3 = 0;
            DataTable dt_put;
            //增加一个合计行 
            dt_put = (DataTable)dgv_tran.DataSource;
            //d_1 = (decimal)dt_put.Compute("Sum(" + dt_put.Columns["socount"].ColumnName + ")", "true");
            //d_2 = (decimal)dt_put.Compute("Sum(" + dt_put.Columns["finish_count"].ColumnName + ")", "true");
            //d_5 = (decimal)dt_put.Compute("Sum(" + dt_put.Columns["freeze_qty_m"].ColumnName + ")", "true");
            //d_6 = (decimal)dt_put.Compute("Sum(" + dt_put.Columns["freeze_qty_s"].ColumnName + ")", "true");
            //d_7 = (decimal)dt_put.Compute("Sum(" + dt_put.Columns["cubage"].ColumnName + ")", "true");
            //d_8 = (decimal)dt_put.Compute("Sum(" + dt_put.Columns["gross_weight"].ColumnName + ")", "true");
            //d_9 = (decimal)dt_put.Compute("Sum(" + dt_put.Columns["net_weight"].ColumnName + ")", "true");
            //d_10 = (decimal)dt_put.Compute("Sum(" + dt_put.Columns["box"].ColumnName + ")", "true");

            for (int i = 0; i < dt_put.Rows.Count; i++)
            {
                d_1 += decimal.Parse(dt_put.Rows[i]["socount"].ToString().Trim());
                d_2 += decimal.Parse(dt_put.Rows[i]["finish_count"].ToString().Trim());
                d_3 += decimal.Parse(dt_put.Rows[i]["sku_count"].ToString().Trim());
            }


            DataRow dr = dt_put.NewRow();
            dr["linename"] = "合计";
            dr["socount"] = d_1.ToString();
            dr["finish_count"] = d_2.ToString();
            dr["sku_count"] = d_3.ToString();
            //dr["freeze_qty_m"] = d_5;
            //dr["freeze_qty_s"] = d_6;
            //dr["cubage"] = d_7;
            //dr["gross_weight"] = d_8;
            //dr["net_weight"] = d_9;
            //dr["box"] = d_10;
            ((DataTable)dgv_tran.DataSource).Rows.InsertAt(dr, ((DataTable)dgv_tran.DataSource).Rows.Count);
        }

        private void w_inv002_Load(object sender, EventArgs e)
        {
            tb_number.Text = "5";
            dscustomer = new DataSet();
            try
            {
                //dscustomer = new DataSet();
                //dscustomer = main.g_class.comm_get_consignor();
                //cb_consignor.DataSource = dscustomer.Tables[0];
                //cb_consignor.ValueMember = "consignor";
                //cb_consignor.DisplayMember = "consignor";

                //语言转换
                main.g_class.comm_changeControl(this, main.g_win_dataset);
            }
            catch (System.Exception ee)
            {
                MessageBox.Show(main.g_class.comm_getchangestring("Fail to initialize Information of transaction type", main.g_info_dataset) + "!" + ee.ToString());
                return;
            }
            
            //dtp_h_time.CustomFormat = "yyyy.MM.dd";
            //dtp_h_time.Format = DateTimePickerFormat.Custom;
            //dtp_h_time_end.CustomFormat = "yyyy.MM.dd";
            //dtp_h_time_end.Format = DateTimePickerFormat.Custom;
            //dtp_h_time.Value = System.Convert.ToDateTime(DateTime.Now.ToString("yyyy.MM.dd").Trim());
            //dtp_h_time_end.Value = System.Convert.ToDateTime(DateTime.Now.AddDays(7).ToString("yyyy.MM.dd").Trim());

            //线路
            //LoadLine();
           
        }

      
        private void cb_consignor_TextChanged(object sender, EventArgs e)
        {
            string str_cust;
            str_cust = cb_consignor.Text.Trim();
            tb_cusname.Text = main.g_class.comm_findname(str_cust, dscustomer);
        }

     
        private void btn_excel_Click(object sender, EventArgs e)
        {
            if (dgv_tran.Rows.Count > 0)
            {
                main.g_class.DataGridViewToExcel(dgv_tran);
            }
        }


        //线路
        private void LoadLine()
        {
            try
            {
                string str_sql;
                DataSet ds_line;
                //列出属于该波次的列表
                str_sql = "select distinct linecode,(linecode + '-' + linename) linename  from  " + main.g_space + ".mst_line  order by linename ";
                if (main.dbtype == "SQL")
                    ds_line = main.dbservice.Sql_exec_selectsql(str_sql);
                else
                    ds_line = main.dbservice.oracle_exec_selectsql(str_sql);

                cbx_line.ValueMember = "linecode";
                cbx_line.DisplayMember = "linename";

                cbx_line.DataSource = ds_line.Tables[0];
                if (cbx_line.Items.Count > 1)
                {
                    cbx_line.Text = "";
                }
            }
            catch (System.Exception ee)
            {
                MessageBox.Show("线路加载失败!" + ee.ToString());
            }
        }


        public string GetStoreFunction()
        {
            //// 接口已废弃不用
            //try
            //{
            //    string[] sUrlArr = main.g_server.Split(':');
            //    if (sUrlArr.Length == 0)
            //        return "";

            //    string sUrl = "http://" + sUrlArr[0] + ":8057/api/getStorePickStatus";
            //    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sUrl);
            //    request.Method = "GET";
            //    request.ContentType = "text/html;charset=UTF-8";
            //    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            //    Stream myResponseStream = response.GetResponseStream();
            //    StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            //    string retString = myStreamReader.ReadToEnd();
            //    myStreamReader.Close();
            //    myResponseStream.Close();
            //    return retString;

            //}
            //catch (Exception ex)
            //{
            //    return "";
            //}

            return "";
        }
        //查询数据
        private void querydata()
        {
            //状态字段
            //linecode              --路线编号
            //linename              --路线名
            //shopcode              --门店号
            //shopname              --门店名
            //totalBillNumbers      --总单据数
            //endTotalBillNumbers   --已完成单据数

            //HOURBill              --单/小时
            //bill_per              --拣货进度

            //totalSKU              --总SKU数
            //totalBreakDownSKU     --总拆零商品数
            //totalCatonSku         --总整件商品数
            //totalBreakQty         --总拆零数
            //totalCatonQty         --总整件数
            //pickendtime           --拣货结束时间
            //pickstarttime         --拣货开始时间
            //totalBoxQty           --总周转箱数

            // 设置为忙碌状态
            Cursor.Current = Cursors.WaitCursor;

            string ret = GetStoreFunction();


            string str_sql = "select t1.linecode,(select top 1 linename from " + main.g_space + ".mst_line where  linecode = t1.linecode) as linename," +
                "shopcode,(select top 1 consignor_name from wms.mst_customer where inv_org='01.01.002.01' and consignor = t1.shopcode ) shopname," +
                "totalBillNumbers,endTotalBillNumbers,(case when isnull(totalBillNumbers,0)>0 then CONVERT(varchar, CAST(isnull(endTotalBillNumbers,0) * 100.0 / totalBillNumbers AS DECIMAL(13, 2))) + '%' else '0.00%'end) AS bill_per,"+
                "totalSKU,totalBreakDownSKU,totalCatonSku,totalBreakQty, totalCatonQty,pickendtime,pickstarttime,totalBoxQty," +
                "(case when DATEDIFF(HOUR, pickstarttime,pickendtime)>0  then endTotalBillNumbers / DATEDIFF(HOUR, pickstarttime,pickendtime) else 0 end) HOURBill " +
                " from " + main.g_space + ".in_getStorePickStatus t1 " +
                " left join " + main.g_space + ".mst_line t2 on t1.linecode = t2.linecode and t1.shopcode = t2.storeCd" +
                " where 1=1 ";

            str_sql += "ORDER BY CONVERT(int,t2.lineSeqno), CONVERT(int,t2.Sequenceno) ";

            try
            {
                if (main.dbtype == "SQL")
                {
                    ds_tran = main.dbservice.Sql_exec_selectsql(str_sql);
                }
                else
                {
                    ds_tran = main.dbservice.oracle_exec_selectsql(str_sql);
                }
                if (ds_tran.Tables[0].Rows.Count > 0)
                    dgv_tran.DataSource = ds_tran.Tables[0];
                else
                    dgv_tran.DataSource = null;
            }
            catch (System.Exception ee)
            {
                MessageBox.Show(main.g_class.comm_getchangestring("Fail to Query", main.g_info_dataset) + "!" + ee.ToString());
            }

            Cursor.Current = currentCursor;

        }

        //查询数据
        private void querydata_wms()
        {
            //状态字段
            //linecode              --路线编号
            //linename              --路线名
            //shopcode              --门店号
            //shopname              --门店名
            //totalBillNumbers      --总单据数
            //endTotalBillNumbers   --已完成单据数

            //HOURBill              --单/小时
            //bill_per              --拣货进度

            //totalSKU              --总SKU数
            //totalBreakDownSKU     --总拆零商品数
            //totalCatonSku         --总整件商品数
            //totalBreakQty         --总拆零数
            //totalCatonQty         --总整件数
            //pickendtime           --拣货结束时间
            //pickstarttime         --拣货开始时间
            //totalBoxQty           --总周转箱数

            // 设置为忙碌状态
            Cursor.Current = Cursors.WaitCursor;

            string ret = GetStoreFunction();


            string str_sql = "select t1.linecode,(select top 1 linename from " + main.g_space + ".mst_line where  linecode = t1.linecode) as linename," +
                "shopcode,(select top 1 consignor_name from wms.mst_customer where inv_org='01.01.002.01' and consignor = t1.shopcode ) shopname," +
                
                "  billnum   as totalBillNumbers , " +
                "  f_billnum as endTotalBillNumbers," +
                "    (" +
                "    CASE" +
                "" +
                "        WHEN isnull(billnum, 0) > 0 THEN " +
                "        CONVERT (VARCHAR, CAST (isnull(f_billnum, 0) * 100.0 / billnum AS DECIMAL (13, 2))) + '%' ELSE '0.00%'  " +
                "      END) AS bill_per, " +
                "  skunum        as totalSKU,           " + //-- 总SKU数
                "  parts_num     as totalBreakDownSKU,  " + // -- 总拆零商品数
                "  whole_num     as totalCatonSku,      " + // -- 总整件商品数
                "  parts_pickqty as totalBreakQty,      " + // -- 总拆零数
                "  whole_pickqty as totalCatonQty,      " + // -- 总整件数
                "  turnoverboxnum as totalBoxQty,       " + // -- 周转箱数
                " " +
                "  pickendtime, " +
                "  pickstarttime, " +
                " (CASE WHEN DATEDIFF(HOUR, pickstarttime, pickendtime) > 0 THEN f_billnum / DATEDIFF(HOUR, pickstarttime, pickendtime) ELSE 0 END) HOURBill " +

                " from " + main.g_space + ".VIEW_SQL_MONITOR_PICKBILL_SHOP t1 " +
                " left join " + main.g_space + ".mst_line t2 on t1.linecode = t2.linecode and t1.shopcode = t2.storeCd" +
                " where 1=1 ";

            str_sql += "ORDER BY CONVERT(int,t2.lineSeqno), CONVERT(int,t2.Sequenceno) ";

            try
            {
                if (main.dbtype == "SQL")
                {
                    ds_tran = main.dbservice.Sql_exec_selectsql(str_sql);
                }
                else
                {
                    ds_tran = main.dbservice.oracle_exec_selectsql(str_sql);
                }
                if (ds_tran.Tables[0].Rows.Count > 0)
                    dgv_tran.DataSource = ds_tran.Tables[0];
                else
                    dgv_tran.DataSource = null;
            }
            catch (System.Exception ee)
            {
                MessageBox.Show(main.g_class.comm_getchangestring("Fail to Query", main.g_info_dataset) + "!" + ee.ToString());
            }

            Cursor.Current = currentCursor;

        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                this.timer1.Enabled = true;
                if (tb_number.Text.Trim() == "" || tb_number.Text.Trim() == "0")
                {
                    tb_number.Text = "5";
                }
                iJS = 0;
                iJSset = int.Parse(tb_number.Text.Trim()) * 60;

                this.timer1.Enabled = true;
                tb_number.Enabled = false;
                btn_Query.Enabled = false;
            }
            else
            {
                iJS = 0;
                this.timer1.Enabled = false;
                tb_number.Enabled = true;
                btn_Query.Enabled = true;
                label1.Text = "";
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (iJS < iJSset)
            {
                iJS += 1;
            }
            else
            {
                iJS = 0;
                //刷新数据
                querydata();
            }
            label1.Text = iJS.ToString();
        }

        private void dgv_tran_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //自动编号，与数据无关
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
               e.RowBounds.Location.Y,
               dgv_tran.RowHeadersWidth - 4,
               e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics,
                  (e.RowIndex + 1).ToString(),
                   dgv_tran.RowHeadersDefaultCellStyle.Font,
                   rectangle,
                   dgv_tran.RowHeadersDefaultCellStyle.ForeColor,
                   TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }


    }
}